package com.hxc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hxc.entity.Clazz;
import com.hxc.entity.ClazzQueryParam;
import com.hxc.entity.PageBean;
import com.hxc.entity.Student;
import com.hxc.mapper.ClazzMapper;
import com.hxc.mapper.StudentMapper;
import com.hxc.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    /**
     * 分页查询
     * */
    @Override
    public PageBean getClazz(ClazzQueryParam param) {
        // pagehelper将结果封装成page对象，继承了ArrayList
        PageHelper.startPage(param.getPage(),param.getPageSize());
        List<Clazz> clazzs = clazzMapper.getClazzPage(param);
        log.info("查询到当前页的{}条信息：",clazzs.size());
        LocalDate localDate = LocalDate.now();
        // 判断当前状态
        for (Clazz clazz : clazzs) {
            if (localDate.isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            }else if (localDate.isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("已开班");
            }
        }
        //
        Page page = (Page) clazzs;
        return new PageBean(page.getTotal(),page.getResult());
    }
    /**
     * 新增班级
     * */
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }
    /**
     * 通过id查询
     * */
    @Override
    public Clazz getClazzById(int id) {
        Clazz clazz = clazzMapper.getClazzById(id);
        return clazz;
    }
    /**
     * 修改班级信息
     * */
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }
    /**
     * 删除班级信息
     * */
    @Override
    public Boolean deleteClazz(int id) {
        List<Student> stus= studentMapper.getStudentByClazzId(id);
        log.info("在当前班级下查询到{}各学生",stus.size());
        if (!stus.isEmpty()){
            return false;
        }
        clazzMapper.deleteClazz(id);
        return true;
    }
    /**
     * 查询所有班级
     * */
    @Override
    public List<Clazz> getAllClazz() {
        List<Clazz> clazzes = clazzMapper.getAllClazz();
        return clazzes;
    }
}
